import { useState, useRef, useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import './ChatPage.css';

// 角色转换：agent→assistant（适配API，保留核心逻辑）
const convertToApiRole = (role) => role === 'agent' ? 'assistant' : 'user';

export default function ChatPage() {
  // 状态管理（只保留必需状态）
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [systemPrompt, setSystemPrompt] = useState('You are a helpful assistant.');
  const chatMessagesRef = useRef(null); // 消息容器ref（滚动用）
  const [searchParams] = useSearchParams();
  const { sessionId, maskId, maskName } = Object.fromEntries([...searchParams]);

  // 加载系统提示（简化冗余错误提示，保留核心逻辑）
  useEffect(() => {
    if (!maskId || !sessionId) return;
    const fetchSystemPrompt = async () => {
      const res = await fetch('http://localhost:5000/api/session/all');
      if (!res.ok) return;
      const sessions = await res.json();
      const targetSession = sessions.find(s => s.mask.id.toString() === maskId);
      const systemCtx = targetSession?.mask.context?.find(ctx => ctx.role === 'system');
      if (systemCtx) setSystemPrompt(systemCtx.content);
    };
    fetchSystemPrompt();
  }, [maskId, sessionId]);

  // 自动滚动到底部（简化注释，保留核心逻辑）
  useEffect(() => {
    const container = chatMessagesRef.current;
    if (container) {
      requestAnimationFrame(() => {
        container.scrollTop = container.scrollHeight;
      });
    }
  }, [messages, isLoading]);

  // 保存消息到后端（简化错误处理，保留核心请求逻辑）
  const saveMessage = async (message) => {
    const res = await fetch(`http://localhost:5000/api/session/message/add?sessionId=${message.sessionId}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(message)
    });
    if (!res.ok) throw new Error(`保存失败: ${res.status}`);
  };

  // 发送消息核心逻辑（简化冗余变量，保留核心流程）
  const sendMessage = async () => {
    const content = input.trim();
    if (!content || isLoading || !sessionId) return;

    // 1. 显示用户消息 + 切换加载状态
    const userMsg = {
      role: 'user',
      content,
      timestamp: new Date(),
      date: new Date().toISOString(),
      sessionId,
      maskId
    };
    setMessages(prev => [...prev, userMsg]);
    setInput('');
    setIsLoading(true);

    try {
      // 2. 保存用户消息到后端
      await saveMessage(userMsg);

      // 3. 构造AI请求参数（系统提示 + 历史消息 + 当前用户消息）
      const apiMsgList = [
        { role: 'system', content: systemPrompt },
        ...messages.map(msg => ({ role: convertToApiRole(msg.role), content: msg.content })),
        { role: 'user', content }
      ];

      // 4. 调用DeepSeek API获取回复
      const aiRes = await fetch('https://api.deepseek.com/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer sk-d230429752104f10b2ab1b8c24b6f813'
        },
        body: JSON.stringify({
          model: 'deepseek-chat',
          messages: apiMsgList,
          stream: false,
          temperature: 0.7,
          max_tokens: 2048
        })
      });

      if (!aiRes.ok) throw new Error(`API请求失败: ${aiRes.status}`);
      const aiData = await aiRes.json();

      // 5. 显示AI回复 + 保存到后端
      const aiMsg = {
        role: 'agent',
        content: aiData.choices[0].message.content,
        timestamp: new Date(),
        date: new Date().toISOString(),
        sessionId,
        maskId
      };
      setMessages(prev => [...prev, aiMsg]);
      await saveMessage(aiMsg);

    } catch (err) {
      // 6. 错误处理：显示错误消息
      setMessages(prev => [...prev, {
        role: 'agent',
        content: `回复失败：${err.message || '未知错误'}`,
        timestamp: new Date(),
        date: new Date().toISOString(),
        sessionId,
        maskId
      }]);
    } finally {
      // 7. 无论成功/失败，都关闭加载状态
      setIsLoading(false);
    }
  };

  // 回车发送（保留核心逻辑）
  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  return (
    <div className="ds_deepseek-chat-container">
      <div className="ds_chat-header">
        <div className="ds_chat-logo"><span>{maskName || '未知面具'}</span></div>
        {!sessionId && <div className="ds_session-warning">警告：未找到会话ID，消息可能无法保存</div>}
      </div>

      <div className="ds_chat-messages" ref={chatMessagesRef}>
        {messages.length === 0 && (
          <div className="ds_empty-messages">
            <p>开始与{maskName || 'AI'}对话吧～</p>
            {systemPrompt !== 'You are a helpful assistant.' && (
              <p className="ds_system-prompt-hint">（AI提示：{systemPrompt}）</p>
            )}
          </div>
        )}

        {messages.map((msg, i) => (
          <div 
            key={i + msg.timestamp.getTime()}
            className={`ds_message ${msg.role === 'user' ? 'ds_user-message' : 'ds_assistant-message'}`}
          >
            <div className="ds_message-sender">{msg.role === 'user' ? '你' : maskName || 'DeepSeek'}</div>
            <div className="ds_message-content">{msg.content}</div>
            <div className="ds_message-time">
              {msg.timestamp.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}
            </div>
          </div>
        ))}

        {/* 加载中状态：AI正在回复时显示 */}
        {isLoading && (
          <div className="ds_message ds_assistant-message ds_loading">
            <div className="ds_message-sender">{maskName || 'DeepSeek'}</div>
            <div className="ds_message-content">
              <div className="ds_typing-indicator"><span>.</span><span>.</span><span>.</span></div>
            </div>
          </div>
        )}
      </div>

      <div className="ds_chat-input-area">
        <textarea
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyPress={handleKeyPress}
          placeholder="输入消息..."
          className="ds_message-input"
          disabled={isLoading || !sessionId}
        />
        <button 
          onClick={sendMessage} 
          className="ds_send-button"
          disabled={!input.trim() || isLoading || !sessionId}
        >
          发送
        </button>
      </div>
    </div>
  );
}